from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
import torch


base_model_path = r"D:\modelscope\Qwen\Qwen3-1___7B"
lora_adapter_path = r"D:\modelscope\magicboxes\Qwen3-1___7B-catgirl-lora"  # 你的 LoRA 适配器路径

print("加载的模型是：", base_model_path)
print("加载的LoRA是：", lora_adapter_path)


# 加载原始模型（必须是非量化版本！）
model = AutoModelForCausalLM.from_pretrained(
    base_model_path,
    device_map="cpu",  # 强制所有模块在 CPU
    torch_dtype=torch.float32,  # CPU 上建议用 float32
    trust_remote_code=True,
)

# 加载 LoRA 适配器
model = PeftModel.from_pretrained(model, lora_adapter_path, device_map="cpu")

# 加载 tokenizer
tokenizer = AutoTokenizer.from_pretrained(base_model_path)

# bugfix
# tokenizer.pad_token = "<|vision_pad|>"
# tokenizer.eos_token = "<|im_end|>"

# tokenizer.chat_template = "{%- if tools %}\n    {{- '<|im_start|>system\\n' }}\n    {%- if messages[0].role == 'system' %}\n        {{- messages[0].content + '\\n\\n' }}\n    {%- endif %}\n    {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n    {%- for tool in tools %}\n        {{- \"\\n\" }}\n        {{- tool | tojson }}\n    {%- endfor %}\n    {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n    {%- if messages[0].role == 'system' %}\n        {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n    {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n    {%- set index = (messages|length - 1) - loop.index0 %}\n    {%- if ns.multi_step_tool and message.role == \"user\" and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n        {%- set ns.multi_step_tool = false %}\n        {%- set ns.last_query_index = index %}\n    {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n    {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n        {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n    {%- elif message.role == \"assistant\" %}\n        {%- set content = message.content %}\n        {%- set reasoning_content = '' %}\n        {%- if message.reasoning_content is defined and message.reasoning_content is not none %}\n            {%- set reasoning_content = message.reasoning_content %}\n        {%- else %}\n            {%- if '</think>' in message.content %}\n                {%- set content = message.content.split('</think>')[-1].lstrip('\\n') %}\n                {%- set reasoning_content = message.content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n            {%- endif %}\n        {%- endif %}\n        {%- if loop.index0 > ns.last_query_index %}\n            {%- if loop.last or (not loop.last and reasoning_content) %}\n                {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n            {%- else %}\n                {{- '<|im_start|>' + message.role + '\\n' + content }}\n            {%- endif %}\n        {%- else %}\n            {{- '<|im_start|>' + message.role + '\\n' + content }}\n        {%- endif %}\n        {%- if message.tool_calls %}\n            {%- for tool_call in message.tool_calls %}\n                {%- if (loop.first and content) or (not loop.first) %}\n                    {{- '\\n' }}\n                {%- endif %}\n                {%- if tool_call.function %}\n                    {%- set tool_call = tool_call.function %}\n                {%- endif %}\n                {{- '<tool_call>\\n{\"name\": \"' }}\n                {{- tool_call.name }}\n                {{- '\", \"arguments\": ' }}\n                {%- if tool_call.arguments is string %}\n                    {{- tool_call.arguments }}\n                {%- else %}\n                    {{- tool_call.arguments | tojson }}\n                {%- endif %}\n                {{- '}\\n</tool_call>' }}\n            {%- endfor %}\n        {%- endif %}\n        {{- '<|im_end|>\\n' }}\n    {%- elif message.role == \"tool\" %}\n        {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n            {{- '<|im_start|>user' }}\n        {%- endif %}\n        {{- '\\n<tool_response>\\n' }}\n        {{- message.content }}\n        {{- '\\n</tool_response>' }}\n        {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n            {{- '<|im_end|>\\n' }}\n        {%- endif %}\n    {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n    {{- '<|im_start|>assistant\\n' }}\n    {%- if enable_thinking is defined and enable_thinking is false %}\n        {{- '<think>\\n\\n</think>\\n\\n' }}\n    {%- endif %}\n{%- endif %}"


# 开始代码
# 照搬教程内的代码
def func1():
  question="爱我爱我爱我"
  def ack_catgirl(question):
      messages = [
          {"role": "user", "content": question}
      ]

      text = tokenizer.apply_chat_template(
          messages,
          tokenize=False,
          add_generation_prompt=True,
          enable_thinking=False,
      )

      return text

  inputs = tokenizer([ack_catgirl(question)], return_tensors="pt").to("cpu")

  outputs = model.generate(
      input_ids=inputs.input_ids,
      attention_mask=inputs.attention_mask,
      max_new_tokens=300,
      use_cache=True,
  )
  response = tokenizer.batch_decode(outputs)

  import re

  start_word = "</think>"
  end_word = "<|im_end|>"

  pattern = rf"{re.escape(start_word)}(.*?){re.escape(end_word)}"
  match = re.search(pattern, response[0], re.DOTALL)

  if match:
      middle_content = match.group(1).strip()
      print("回答：", middle_content)
  else:
      print("未找到匹配模型输出内容：", response[0])


# 自己拼接的测试
def func2():
  str_msg = """
<|im_start|>user
沐雪的功能是什么？<|im_end|>
<|im_start|>assistant
<think>

</think>
"""
  inputs = tokenizer(str_msg, return_tensors="pt").to("cpu")
  outputs = model.generate(**inputs, max_new_tokens=150,
                          repetition_penalty=1.5,
                          do_sample=True,
                          temperature = 0.7, top_p = 0.8, top_k = 20, # 普通对话模式参数
                          eos_token_id = tokenizer.eos_token_id,
                          pad_token_id = tokenizer.pad_token_id,
                            )
  print("最小化输出：", tokenizer.decode(outputs[0]))



# 照抄官网给出的推理代码
def func3():
  messages = [
    {"role": "user", "content": "爱我爱我爱我"}
  ]

  text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
    enable_thinking=False, # Switches between thinking and non-thinking modes. Default is True.
  )
  model_inputs = tokenizer([text], return_tensors="pt").to(model.device)

  # conduct text completion
  generated_ids = model.generate(
      **model_inputs,
      max_new_tokens=600,
  )
  output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist() 

  # parse thinking content
  try:
      # rindex finding 151668 (</think>)
      index = len(output_ids) - output_ids[::-1].index(151668)
  except ValueError:
      index = 0

  thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
  content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")

  print("thinking content:", thinking_content)
  print("content:", content)

func3()
